import React from 'react';
import {View} from "@gluestack-ui/themed";
import {LineChartProps, LineChartState} from "@/components/data-panel/type";
import {useQuery, useTheme} from "@/hooks";
import * as echarts from 'echarts/core';
import {LineChart} from 'echarts/charts';
import {GridComponent, TooltipComponent, LegendComponent} from 'echarts/components';
import {SVGRenderer, SvgChart} from '@wuba/react-native-echarts';
import {useImmer} from "use-immer";
import {ChartData} from "@/types/chart";
import {LayoutChangeEvent} from "react-native/Libraries/Types/CoreEventTypes";

echarts.use([SVGRenderer, LineChart, GridComponent, TooltipComponent, LegendComponent]);

const KLineChart = <P, >(props: LineChartProps<P>) => {
    const {colors} = useTheme();
    const {
        show = true,
        api,
        params,
        themeColors = [colors.primary500, colors.blue500],
        labelMaps,
        height = 250
    } = props;
    const skiaRef = React.useRef<any>(null);

    // 轴刻线样式
    const axisLabelStyle = {
        color: colors.textLight400,
        fontSize: 10,
        hideOverlap: true,
    }
    // 轴网格配置
    const axisGirdConfig = {
        show: true,
        interval: 0,  // 确保显示所有的网格线
        lineStyle: {
            type: 'dashed' as const, // 设置网格线线型为虚线
            color: colors.textLight100,
            width: 0.5,
        }
    }

    const [{chartData, chart, finish, options, width}, updateData] = useImmer<LineChartState<echarts.ECharts>>({
        chartData: null,
        chart: null,
        width: 300,
        finish: false,
        options: {
            animation:false,
            grid: {
                left: '15%', // 增加左侧空白区域
                right: '15%', // 增加右侧空白区域
                bottom: 20
            },
            legend: {
                top: 10,
                itemWidth: 10,
                itemHeight: 10,
                left: "5%",
                padding: 0,
                textStyle: axisLabelStyle,
                icon: "circle",
                data: [],
            },
            color: themeColors,
            tooltip: {
                trigger: 'axis',
                textStyle: {
                    fontSize: 10,
                    color: colors.white
                },
                backgroundColor: "rgba(0,0,0,0.5)"
            },
            xAxis: {
                type: 'category',
                data: [],
                axisLabel: axisLabelStyle,
                splitLine: axisGirdConfig,
                axisLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                axisPointer: {
                    lineStyle: {
                        color: colors.textLight300,
                        type: "solid"
                    }
                }
            },
            yAxis: [],
            series: [],
        }
    });

    const {data: chartRes, isLoading, isFetching, Loading, isSuccess} = useQuery(api, params, {
        enabled: show, // 禁用自动请求
        queryKey: [params, labelMaps],
        staleTime: 5000, // 5秒内认为数据是新鲜的，不会重新获取
    });

    React.useEffect(() => {
        if (isSuccess) {
            handleResData(chartRes.data);
        }
    }, [isSuccess])

    const getSkiaRef = React.useCallback((ref: any) => {
        skiaRef.current = ref;
        if (skiaRef.current) {
            initChart();
        }
        return () => chart?.dispose();
        // 现在你可以访问实例了
    }, [chartData, height, options]);

    function initChart() {
        let charts = echarts.init(skiaRef.current, 'light', {
            renderer: 'svg',
            width,
            height,
        });
        charts.setOption(options);
        updateData(draft => {
            draft.chart = charts;
        });
    }


    // 处理相应数据
    function handleResData(data: ChartData) {
        updateData(draft => {
            draft.chartData = data;
            // @ts-ignore
            draft.options.xAxis!.data = data.categories;
            draft.options.yAxis = data.series.map(item => ({
                name: labelMaps[item.name],
                type: "value",
                axisLabel: axisLabelStyle,
                splitLine: axisGirdConfig,
                nameTextStyle: axisLabelStyle,

            }));
            draft.options.series = data.series.map((item, index) => ({
                name: labelMaps[item.name],
                data: item.data,
                type: 'line',
                smooth: true,
                yAxisIndex: index,
                symbol:"none"
            }));
            // @ts-ignore
            draft.options.legend!.data = data.series.map(item => labelMaps[item.name]);
            draft.finish = true;
        });
    }

    function handleChartLoad(e: LayoutChangeEvent) {
        if (!e.nativeEvent) return;
        updateData(draft => {
            draft.width = e.nativeEvent.layout.width;
        })
    }

    return (
        <View h={height} display={show ? "flex" : "none"} onLayout={handleChartLoad}>
            {(isLoading || !finish) && <Loading loading={isLoading}/>}
            {(!isLoading && show && finish) && <SvgChart ref={getSkiaRef}/>}
        </View>

    );
};


export default KLineChart;